import "./outer.css";
import { ReactComponent as TopSvg } from "../../common/svg/top-arrow.svg";
import { useEffect, useState } from "react";

function Outer() {
  const [show, setShow] = useState(false);

  useEffect(() => {
    window.addEventListener("scroll", changeScrollTopShow);

    return () => window.removeEventListener("scroll", changeScrollTopShow);
  }, [])

  const changeScrollTopShow = () => {
    if (window.pageYOffset < 400) {
      setShow(false);
    } else {
      setShow(true);
    }
  }

  const scrollToTop = () => {
    const scrollToTop = window.setInterval(() => {
      let pos = window.pageYOffset;
      if (pos > 0) {
        window.scrollTo(0, pos - 20);
      } else {
        window.clearInterval(scrollToTop);
      }
    }, 1);
  }

  return (
    <div className="button-outer">
      <div className="button-inner">
        <div className="button-wrap">
          {show ? (
            <button className="top-btn" onClick={scrollToTop}>
              <TopSvg />
              <span className="btn-text">顶部</span>
            </button>
          ) : null}
        </div>
      </div>
    </div>
  )
}

export default Outer;